/*
 * Copyright (c) 2011 Ball State University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * NOTE:
 * Derivative work based on the Google IO 2011 Schedule app released for open source
 * http://code.google.com/p/iosched/
 */

package edu.bsu.android.gtv.apps.bconnected.ui;

import java.util.ArrayList;

import edu.bsu.android.gtv.apps.bconnected.R;
import edu.bsu.android.gtv.apps.bconnected.data.CategoryData;
import edu.bsu.android.gtv.apps.bconnected.objects.Category;
import edu.bsu.android.gtv.apps.bconnected.objects.Person;
import edu.bsu.android.gtv.apps.bconnected.util.Adapters;
import edu.bsu.android.gtv.apps.bconnected.util.AnalyticsUtils;
import edu.bsu.android.gtv.apps.bconnected.util.Constants;
import edu.bsu.android.gtv.apps.bconnected.util.DisclaimerHelper;
import edu.bsu.android.gtv.apps.bconnected.util.LoginHelper;
import edu.bsu.android.gtv.apps.bconnected.util.PersistentListFragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

/**
 * A simple {@link PersistentListFragment} that renders a list of categories.  The listfragment appears in the left hand column of the 
 * {@link OrganizationMultiPaneActivity} and when an item is selected, a list of organizations appears using the {@link OrganizationFragment} in the 
 * right hand column.
 * @author Kyle Parker, University Computing Services
 */
public class CategoryFragment extends PersistentListFragment {
    private static final String TAG = "CategoryFragment";
    
    private Bundle mBundle = null;
	private OnCategoryListener mCategoryListener = null;
    private Adapters.CategoryAdapter mAdapter;
    private ArrayList<Category> mCategories;
    private Activity mActivity;
    private BroadcastReceiver mReceiver;
    
    private boolean mLogin;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        mActivity = getActivity();
		this.mBundle = savedInstanceState;
		
        handleLogout();    
        handleLogin();
        
    	if (!DisclaimerHelper.hasAcceptedDisclaimer(mActivity)) {
    		DisclaimerHelper.showDisclaimer(false, mActivity);
    	}
        
        AnalyticsUtils.getInstance(mActivity).trackPageView("/Categories");

        if (mLogin) {
        	loadCategories();
            
            // Set the list style
	    	Drawable selector = mActivity.getResources().getDrawable(R.drawable.left_pane_gradient_background); 
	    	//Drawable selector = mActivity.getResources().getDrawable(R.drawable.list_selector_background_default);
        	getListView().setBackgroundDrawable(selector);
            setListShown(false);
    		
    		if (mCategoryListener != null) {
    			mCategoryListener.onCategorySelected(0);
    			getListView().setItemChecked(0, true);
    		}
        }
    }
	
	@Override
	public void onResume() {
		super.onResume();
		
		restoreState(mBundle);
	}
    
    @Override 
    public void onDestroy() {
    	super.onResume();
    	mActivity.unregisterReceiver(mReceiver);
    }

    /** {@inheritDoc} */
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		if (mCategoryListener != null) {
			mCategoryListener.onCategorySelected(position);
		}
    }

    /**
     * Using a new thread, separate from the main activity, load the categories from the service handler
     */
    private void loadCategories() {
    	mCategories = new ArrayList<Category>();
        mAdapter = new Adapters.CategoryAdapter(mActivity, R.layout.list_item, mCategories);
        setListAdapter(this.mAdapter);
        
        Runnable load = new Runnable(){
            public void run() {
            	try {
	                CategoryData.initializeCategory(mActivity);
	    	    	
	                if (CategoryData.getCategoryCount() > 0) {
	                	mCategories = CategoryData.getCategories();
	                }
	            	
	        		mActivity.runOnUiThread(returnCategory);
            	} catch (Exception ex) {
                    AnalyticsUtils.getInstance(mActivity).trackPageView(TAG + ": " + ex.getMessage());
            	}
            }
        };
        
        Thread thread =  new Thread(null, load, "loadCategories");
        thread.start();
    }
    
    /**
     * Add each term object from the service handler to the array adapter and set the visibility of the spinner to "gone"
     */
    private Runnable returnCategory = new Runnable() {
        public void run() {
            if (mCategories != null && mCategories.size() > 0){
                for (int i=0; i < mCategories.size(); i++)
                {
                	mAdapter.add(mCategories.get(i));
                }
            }

            mAdapter.notifyDataSetChanged();
            setListShown(true);
            getListView().setFocusable(true);
            getListView().requestFocus();
        }
    };
    
	public void setOnCategoryListener(OnCategoryListener listener) {
		this.mCategoryListener = listener;
	}
	
	public interface OnCategoryListener {
		void onCategorySelected(int position);
	}

    /**
     * In order to protect the activity from the back stack after a student logs out, remove the activity 
     * If the student hits the back button, this will take them to the Home activity
     */
    private void handleLogout() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_LOGOUT);
        mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
		        intent = new Intent(Intent.ACTION_VIEW, null, mActivity, HomeActivity.class);
		        intent.putExtra(Constants.EXTRA_LOGIN_STATUS, Integer.toString(Constants.LOGIN_STATUS_LOGOUT));
		        
		        mActivity.startActivity(intent); 
			    mActivity.finish();
			}
		};
		
        mActivity.registerReceiver(mReceiver, intentFilter);
    }
    
    /**
     * Determine if the person has logged in and whether there is a person object in the database
     * Get the student's BSU ID for use throughout the application
     */
    private void handleLogin() {
    	Person person = LoginHelper.checkLogin(mActivity);
    	
    	if (person != null) {
        	mLogin = true;
    	} else {
	        Intent intent = new Intent(Intent.ACTION_VIEW, null, mActivity, HomeActivity.class);
	        intent.putExtra(Constants.EXTRA_LOGIN_STATUS, Integer.toString(Constants.LOGIN_STATUS_NOT_LOGGED_IN));
	        
	        mActivity.startActivity(intent); 
		    mActivity.finish();
		    
		    mLogin = false;
    	} 	
    }
}
